package edu.po.au.server.service;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.response.CollectionResponse;

import edu.po.au.server.PMF;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.response.CollectionResponse;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.datanucleus.query.JDOCursorHelper;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Nullable;
import javax.inject.Named;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import edu.po.au.server.EPConstants;
import edu.po.au.server.domain.Category;
import edu.po.au.server.domain.User;


@Api(name = "au", version=EPConstants.API_VERSION, 
clientIds = {com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID, EPConstants.WEB_CLIENT_ID}, 
audiences = {EPConstants.ANDROID_AUDIENCE}, 
scopes={"https://www.googleapis.com/auth/userinfo.email"})
public class CategoryEndpoint {
	
	@SuppressWarnings({ "unchecked", "unused" })
  @ApiMethod(name = "category.list", path="category/list")
	public CollectionResponse<Category> listCategory(
													@Nullable @Named("cursor") String cursorString,
													@Nullable @Named("limit") Integer limit){

			PersistenceManager mgr = null;
			Cursor cursor = null;
			List<Category> execute = null;

			try{
				mgr = getPersistenceManager();
				Query query = mgr.newQuery(Category.class);
				execute = (List<Category>) query.execute();
				cursor = JDOCursorHelper.getCursor(execute);
				
				if (cursorString != null && cursorString != "") {
					cursor = Cursor.fromWebSafeString(cursorString);
					HashMap<String, Object> extensionMap = new HashMap<String, Object>();
					extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
					query.setExtensions(extensionMap);
				}
				
				if (limit != null) {
					query.setRange(0, limit);
				}
				
				// Tight loop for fetching all entities from datastore and accomodate for lazy fetch.
				for (Category obj : execute)
				;
			}
			finally{
				mgr.close();
			}		
			
			return CollectionResponse.<Category> builder().setItems(execute).setNextPageToken(cursorString).build();
	}
	
	@SuppressWarnings({ "unchecked", "unused" })
  @ApiMethod(name = "category.insert", path="category/insert")
	public Category insetCategory(Category category){
		PersistenceManager mgr = getPersistenceManager();
		if(containsCategory(category))
			throw new EntityExistsException("Object already exists");
		mgr.makePersistent(category);
		return category;
		
	}
	
	private boolean containsCategory(Category category) {
		PersistenceManager mgr = getPersistenceManager();
		boolean contains = true;
		try {
			mgr.getObjectById(Category.class, category.getCategoryId());
		} catch (javax.jdo.JDOObjectNotFoundException ex) {
			contains = false;
		} finally {
			mgr.close();
		}
		return contains;
	}
	
	private static PersistenceManager getPersistenceManager(){
		return PMF.get().getPersistenceManager();
		
	}
	
}

